import React, { Component } from 'react'
import { Card, Tabs } from 'antd'
const TabPane = Tabs.TabPane

class Tab extends Component {
    constructor(props) {
        super(props);
        this.newTabIndex = 0;
        const panes = [
            { title: 'Tab 1', content: 'Content of Tab 1', key: '1' },
            { title: 'Tab 2', content: 'Content of Tab 2', key: '2' },
            { title: 'Tab 3', content: 'Content of Tab 3', key: '3' },
        ];
        this.state = {
            activeKey: panes[0].key,
            panes,
        };
    }
    callabck = (key) => {
        console.log(key)
    }
    onChange = (activeKey) => {
        this.setState({
            activeKey
        })
    }
    onEdit = (targetKey, action) => {
        this[action](targetKey);
    }
    add = () => {
        const panes = this.state.panes;
        const activeKey = `newTab${this.newTabIndex ++ }`
        panes.push({ title: 'Tab X', content: 'Content of Tab X', key: activeKey })
        this.setState({
            activeKey,
            panes
        })
    }
    remove = (targetKey) => {
        let activeKey  = this.state.activeKey;
        let lastIndex;
        //先检测其点击的是第几个元素
        this.state.panes.forEach((pane, i)=>{
            // console.log(targetKey)  //targetKey是点击的第几个元素，从1开始
            if(pane.key === targetKey){
                lastIndex = i - 1;
            }
        })
        //过滤掉panes中的需要删除的元素
        const panes = this.state.panes.filter( pane => pane.key !== targetKey )
        //告诉store,显示哪个tab头
        if(lastIndex >=0 && activeKey === targetKey){
            activeKey = panes[lastIndex].key
        }
        this.setState({
            activeKey,
            panes
        })

    }
    render() {
        return (
            <div>
                <Card title="标签页组件" className="card-wrap">
                    <Tabs defaultActiveKey="1" onChange={this.callabck}>
                        <TabPane tab="tab_1" key="1">1</TabPane>
                        <TabPane tab="tab_2" key="2">2</TabPane>
                    </Tabs>
                </Card>
                <Card title="新增/关闭标签页" className="card-wrap">
                    <Tabs
                        onChange={this.onChange}
                        activeKey={this.state.activeKey}
                        type="editable-card"
                        onEdit={this.onEdit}
                    >
                        {this.state.panes.map((item, index) => <TabPane tab={item.title} key={item.key}>{item.content}</TabPane>)}
                    </Tabs>
                </Card>
            </div>
        )
    }
}

export default Tab;